package com.spring.crm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring.crm.conf.CommonResult;
import com.spring.crm.entity.SalesV;
import com.spring.crm.mapper.SalesVMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * VIEW 前端控制器
 * </p>
 *
 * @author 何卓
 * @since 2022-01-16
 */
@RestController
@RequestMapping("/api/crm/sales-v")
public class SalesVController {


    @Resource
    private SalesVMapper salesVMapper;
    
    @CrossOrigin(origins = "*")
    @GetMapping("condition")
    public CommonResult selectByCondition(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,
                                          @CookieValue(value = "userId",defaultValue = "") String userId,
                                          @RequestParam Map<String,String> map) {
        CommonResult rs;
        try {
            String[] authArr = userAuth.split(",");
            if(!Arrays.asList(authArr).contains("f")) {
                map.put("salesman_id", "userId");
            }
            QueryWrapper<SalesV> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("salesId")){
                queryWrapper.eq("sales_id",map.get("salesId"));
            }
            if(map.containsKey("customId")){
                queryWrapper.eq("custom_id",map.get("customId"));
            }
            if(map.containsKey("salesStatus")){
                queryWrapper.eq("sales_status",map.get("salesStatus"));
            }
            if(map.containsKey("salesProcessId")){
                queryWrapper.eq("sales_process_id",map.get("salesProcessId"));
            }
            if(map.containsKey("salesmanId")){
                queryWrapper.eq("salesman_id",map.get("salesmanId"));
            }
            //queryWrapper.orderByAsc("num");
            Page<SalesV> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("size")));
            IPage<SalesV> SalesIPage = salesVMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(salesVMapper.selectCount(queryWrapper));
            List<SalesV> list = SalesIPage.getRecords();
            rs = CommonResult.success(list,selectCount);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
}
